package com.sita.cfmoto.my.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.afollestad.materialdialogs.MaterialDialog;
import com.edmodo.cropper.CropImageView;
import com.google.gson.Gson;
import com.sita.cfmoto.R;
import com.sita.cfmoto.event.LogoutEvent;
import com.sita.cfmoto.event.UpdateProfileEvent;
import com.sita.cfmoto.persistence.User;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.Account;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.BitmapUtils;
import com.sita.cfmoto.utils.JsonUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.LogUtils;
import com.sita.cfmoto.utils.PersistUtils;
import com.sita.cfmoto.my.UpdateUserParams;
import com.sita.cfmoto.utils.TextUtils;
import com.squareup.picasso.Picasso;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

public class UserInfoActivity extends AppCompatActivity {
    @Bind(R.id.avatar_img)
    CircleImageView avatar;
    @Bind(R.id.nick_name_txt)
    EditText nickName;
    @Bind(R.id.pop_parent)
    RelativeLayout popParent;
    private boolean isAccountChanged;
    private Account editAccount = new Account();
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        User user = PersistUtils.getUsers().get(0);
        Picasso.with(GlobalContext.getGlobalContext()).load(user.getAvatar()).centerCrop().fit()
                .into(avatar);
        nickName.setText(user.getNickName());
        password = user.getXmppPass();
    }

    @OnClick(R.id.back_img)
    void onClickBack() {
        finish();
    }

    @OnClick(R.id.logout_btn)
    void onClickLogout() {
        EventBus.getDefault().post(new LogoutEvent());
        finish();
    }

    @OnClick(R.id.avatar_img)
    void onClickAvatar() {
        openPhotoPopup();
    }

    @OnClick(R.id.finish)
    void onClickFinish() {
        editAccount.setNickName(TextUtils.nullIfEmpty(nickName.getText().toString()));
        editAccount.setAvatar(TextUtils.nullIfEmpty((String) avatar.getTag()));
        editAccount.setAccountId(TextUtils.nullIfEmpty(String.valueOf(LocalStorage.getAccountId())));
        doUpdateProfile();
    }

    private void openPhotoPopup() {
        PopupWindow pop = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_dynamic_pic_pop, null);
        LinearLayout popupLayout = (LinearLayout) view.findViewById(R.id.popup_layout);
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);
        pop.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        pop.update();

        RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.item_layout);
        Button btCam = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button btPhoto = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button btCancel = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btCam.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // take photo
                clickTakePhoto();
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clickPickFromGallery();
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
    }

    protected void clickTakePhoto() {
        /**Permission check only required if saving pictures to root of sdcard*/
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            EasyImage.openCamera(this, 0);
            getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
        } else {
            Nammu.askForPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                @Override
                public void permissionGranted() {
                    EasyImage.openCamera(UserInfoActivity.this, 0);
                    getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
                }

                @Override
                public void permissionRefused() {

                }
            });
        }
    }

    protected void clickPickFromGallery() {
        /** Some devices such as Samsungs which have their own gallery app require write permission. Testing is advised! */
        getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
        EasyImage.openGallery(this, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source, int type) {
                //Handle the image
                isAccountChanged = true;
//                Picasso.with(GlobalContext.getGlobalContext())
//                        .load(imageFile).centerInside()
//                        .fit()
//                        .into(avatar);
//                avatar.setTag(imageFile.getAbsolutePath());
                showCropWindow(imageFile);
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source, int type) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(UserInfoActivity.this);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }


    private File avatarSaveToLocal() {
        String IMAGE_FILE_NAME = "temp_header.jpg";
        File headImageFile = BitmapUtils.saveBmpFile(((BitmapDrawable) avatar.getDrawable()).getBitmap(), IMAGE_FILE_NAME);
        return headImageFile;
    }


    private void doUpdateProfile() {

        final MaterialDialog uploadDialog = new MaterialDialog.
                Builder(this).
                content("正在更新...").
                progress(true, 5000).
                build();
        uploadDialog.show();

        TypedFile avatar = null;
        if (isAccountChanged) {
            File headImageFile = avatarSaveToLocal();
            avatar = (headImageFile.equals("")) ? null : new TypedFile("image/jpg", headImageFile);
        }

        UpdateUserParams params = new UpdateUserParams();
        params.accountId = editAccount.getAccountId();
        params.nickName = editAccount.getNickName();
        params.password = password;

        String reqStr = RestClient.getGson().toJson(params);

        TypedString typedString = new TypedString(reqStr);

        RestClient.getRestService().updateProfile(avatar, typedString, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200 && restResponse.mErrorCode.equals("0")) {
                    Gson gson = JsonUtils.getGson();
                    String s = gson.toJson(restResponse.mData);
                    Account account = gson.fromJson(s, Account.class);
                    updateStorage(account.getAccountId(), account.getNickName(), account.getMobile(), account.getAvatar(), account.getImPassword());
                    EventBus.getDefault().post(new UpdateProfileEvent(account.getAvatar(), account.getNickName()));
                    uploadDialog.dismiss();

                } else {
                    uploadDialog.dismiss();
                }
                finish();
            }

            @Override
            public void failure(RetrofitError error) {
                uploadDialog.dismiss();
                LogUtils.d("response", error.getMessage());
            }
        });

    }

    private void updateStorage(String accountId, String nickname, String mobile, String avatar, String password) {
        User user = new User();
        user.setAccountId(Long.valueOf(accountId));
        user.setMobile(mobile);
        user.setAvatar(avatar);
        user.setNickName(nickname);
        user.setXmppPass(password);
        user.setXmppUser(accountId);
        PersistUtils.saveUser(user);
    }

    private void showCropWindow(File imageFile) {
        PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.window_image_cropper, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);
        popupWindow.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        popupWindow.update();
        CropImageView cropImageView = (CropImageView) view.findViewById(R.id.cropImageView);
        cropImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        File mFile = new File(imageFile.getAbsolutePath());
        if (mFile.exists()) {//若该文件存在
            Bitmap bm = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            cropImageView.setImageBitmap(bm);
        }
        cropImageView.setFixedAspectRatio(true);
        cropImageView.setGuidelines(CropImageView.DEFAULT_GUIDELINES);
        cropImageView.setAspectRatio(1, 1);
        view.findViewById(R.id.crop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取裁剪成的图片
                Bitmap croppedImage = cropImageView.getCroppedImage();
                //压缩图片
               Bitmap compressedBitmap =  BitmapUtils.compressBitmap(croppedImage, 200, 200);
                avatar.setImageBitmap(compressedBitmap);
                popupWindow.dismiss();
            }
        });
    }
}
